<template>
  <div class="resource">
    <div class="resource-list">
      <el-card class="box-card">
        <template
          #header
          class="clearfix"
        >
          <el-form
            ref="formDom"
            :model="form"
            label-width="80px"
            inline
          >
            <el-form-item
              prop="phone"
              label="手机号"
            >
              <el-input
                v-model="form.phone"
                placeholder="请输入手机号"
              />
            </el-form-item>
            <el-form-item
              prop="time"
              label="注册时间"
            >
              <el-date-picker
                v-model="form.time"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :shortcuts="shortcuts"
              />
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                :disabled="isLoading"
                @click="onSubmit"
              >
                查询搜索
              </el-button>
              <el-button
                :disabled="isLoading"
                @click="onReset"
              >
                重置
              </el-button>
            </el-form-item>
          </el-form>
        </template>
        <el-table
          v-loading="isLoading"
          :data="users"
          style="width: 100%"
        >
          <el-table-column
            prop="id"
            label="用户ID"
          />
          <el-table-column
            prop="url"
            label="头像"
          >
            <template #default="{row}">
              <img
                :src="row.portrait || '/@/assets/logo.png'"
                style="width: 30px;heigh: 30px;"
              >
            </template>
          </el-table-column>
          <el-table-column
            prop="name"
            label="用户名"
          />
          <el-table-column
            prop="phone"
            label="手机号"
          />
          <el-table-column
            prop="createTime"
            label="注册时间"
          >
            <template #default="row">
              {{ formatDate(row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column
            prop="status"
            label="状态"
          />
          <el-table-column
            label="操作"
          >
            <template #default="{ row }">
              <el-button
                v-if="row.status === 'ENABLE'"
                size="mini"
                type="text"
              >
                禁用
              </el-button>
              <el-button
                size="mini"
                type="text"
                @click="dialogShow(row.id)"
              >
                分配角色
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
          v-model:current-page="form.currentPage"
          :disabled="isLoading"
          :page-sizes="[10, 20, 30]"
          :page-size="form.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalCount"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-card>
    </div>
  </div>
  <!-- 分配角色 -->
  <el-dialog
    v-model="dialogVisible"
    title="分配角色"
  >
    <el-select
      v-model="roleIdList"
      placeholder="请选择角色！"
      style="width: 80%"
      multiple
    >
      <el-option
        v-for="role in allRoles"
        :key="role.code"
        :label="role.name"
        :value="role.id"
      />
    </el-select>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="onAssign"
        >确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts">
import { DefineComponent, defineComponent, onBeforeMount, Ref, ref } from 'vue'
import { getUserPages, getRoleByUserId } from '/@/services/user'
import { getAllRoles, allocateUserRoles } from '/@/services/role'
import { formatDate } from '/@/utils/dayjs'
import { ElMessage } from 'element-plus'
interface SearchForm {
  currentPage: number
  pageSize: number
  phone?: number | null
  time?: null | [Date, Date]
}
let form: Ref<SearchForm>
const formDom = ref<DefineComponent|null>(null)
const useDialog = () => {
  const dialogVisible = ref(false)
  const allRoles = ref([])
  const roleIdList = ref([])
  let instanceUserId: number
  const fetchAllRoles = async () => {
    const { data } = await getAllRoles()
    if (data.code === '000000') allRoles.value = data.data
    console.log(data)
  }

  const getRoleById = async (userId: number) => {
    const { data } = await getRoleByUserId(userId)
    if (data.code === '000000') {
      roleIdList.value = data.data.map((i: any) => i.id)
    }
  }
  const dialogShow = async (userId: number) => {
    instanceUserId = userId
    if (!allRoles.value.length) await fetchAllRoles()
    await getRoleById(userId)
    dialogVisible.value = true
  }
  const onAssign = async () => {
    const { data } = await allocateUserRoles({
      userId: instanceUserId,
      roleIdList: roleIdList.value
    })
    data.code === '000000'
      ? ElMessage.success('分配成功') && (dialogVisible.value = false)
      : ElMessage.error('分配失败')
  }
  return {
    dialogShow,
    roleIdList,
    allRoles,
    dialogVisible,
    onAssign
  }
}
const useDataHandle = () => {
  const isLoading = ref(false)
  const users = ref([])
  const totalCount = ref(0)
  const time = ref<[string, string] | null>()
  const getList = async (form: SearchForm) => {
    isLoading.value = true // 展示加载中状态
    const params = {
      ...form,
      startCreateTime: form.time ? (form?.time as [Date, Date])[0] : '',
      endCreateTime: form.time ? (form?.time as [Date, Date])[1] : ''
    }
    delete params.time
    const { data } = await getUserPages(params)
    params.time = null
    users.value = data.data.records
    totalCount.value = data.data.total
    isLoading.value = false // 关闭加载中状态
  }
  const handleCurrentChange = () => {
    // form.value.currentPage = 1 // 每页大小改变重新查询第1页数据
    getList(form.value)
  }
  const handleSizeChange = (val: number) => {
    form.value.pageSize = val
    form.value.currentPage = 1 // 每页大小改变重新查询第1页数据
    getList(form.value)
  }
  const handleEdit = () => {
    console.log('edit')
  }
  const onSubmit = () => {
    getList(form.value)
  }
  const onReset = () => {
    (formDom.value as DefineComponent).resetFields()
    time.value = null
    console.log('onReset')
  }
  onBeforeMount(() => {
    getList(form.value)
  })
  return {
    time,
    onSubmit,
    onReset,
    isLoading,
    users,
    totalCount,
    handleSizeChange,
    handleCurrentChange,
    handleEdit
  }
}
const shortcuts = [{
  text: '最近一周',
  value: (() => {
    const end = new Date()
    const start = new Date()
    start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
    return [start, end]
  })()
}, {
  text: '最近一个月',
  value: (() => {
    const end = new Date()
    const start = new Date()
    start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
    return [start, end]
  })()
}, {
  text: '最近三个月',
  value: (() => {
    const end = new Date()
    const start = new Date()
    start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
    return [start, end]
  })()
}]
export default defineComponent({
  name: 'ResourceIndex',
  setup () {
    form = ref<SearchForm>({ currentPage: 0, pageSize: 10, phone: null, time: null })
    return {
      form,
      formDom,
      formatDate,
      shortcuts,
      ...useDataHandle(),
      ...useDialog()
    }
  }
})
</script>

<style lang="scss" scoped></style>
